


//
//  TableViewController.m
//  j绝版新闻客户端
//
//  Created by weige on 16/5/10.
//  Copyright © 2016年 weige. All rights reserved.
//

#import "TableViewController.h"

@interface TableViewController ()

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.allNews=[NSMutableArray array];
    //定制表格的线 没有新闻时不显示线
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    
    self.navigationItem.title=@"新闻";
   
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0F],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    //[[UIBarButtonItem appearance]setTitleTextAttributes:@{[NSFontAttributeName:[UIFont systemFontOfSize:14.0F],NSForegroundColorAttributeName:[UIColor ]]} forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(fish) name:@"DOWNLOADFINISH" object:nil];
    
}
-(void)fish
{
    
}
-(void)clear
{
    [self.allNews removeAllObjects];
    [self.tableView reloadData];
    
    
}
-(void)loadNewFromURL:(NSURL*)url
{
    Reachability *reacha=[Reachability reachabilityWithHostname:@"www.qq.com"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSURLSession *session=[NSURLSession sharedSession];
    //设置缓存策略 有缓存 用缓存没有缓存重新请求
    request.cachePolicy=NSURLRequestReturnCacheDataElseLoad;
    //设置缓存 获得全局的缓存对象
    NSURLCache *cache=[NSURLCache sharedURLCache];
    // 获得缓存响应
    NSCachedURLResponse *reponse=[cache cachedResponseForRequest:request ];
    if (reponse) {
        
        NSLog(@"有缓存");
    }
    else
    {
        NSLog(@"没有缓存");
    }
    if (reacha.currentReachabilityStatus==NotReachable) {
        
        [self actionData:reponse.data];
        
    }
    else if (reacha.currentReachabilityStatus>0){
        
        
        
        NSURLSessionDataTask *dask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                //缓存
                [cache storeCachedResponse:[[NSCachedURLResponse alloc] initWithResponse:response data:data] forRequest:request];
                
            });
            
            [self performSelectorOnMainThread:@selector(actionData:) withObject:data waitUntilDone:YES];
        }];
        [dask resume];
        
        [SVProgressHUD showWithStatus:@"正在加载..." maskType:SVProgressHUDMaskTypeBlack];
        
    }
}
-(void)actionData:(NSData *)data
{
    if (data) {
        
        NSArray *arrnew=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if (arrnew) {
            for(NSDictionary *dict in arrnew)
            {
                NewsModel *news=[[NewsModel alloc]init];
                [news setValuesForKeysWithDictionary:dict];
                NSURL *imgUrl=[NSURL URLWithString:news.picture];
                NSMutableURLRequest *requset=[NSMutableURLRequest requestWithURL:imgUrl];
                
                requset.cachePolicy=NSURLRequestReturnCacheDataElseLoad;
                NSURLCache *cache=[NSURLCache sharedURLCache ];
                NSCachedURLResponse *reponse=[cache cachedResponseForRequest:requset];
                if (reponse) {
                    
                    news.data=reponse.data;
                }
                else
                {
                    NSURLSession *session=[NSURLSession sharedSession];
                    NSURLSessionDataTask *dask=[session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                        news.data=data;
                        //发通知
                        
                    }];
                    
                    [dask resume];
                    
                }
                
                
                [self.allNews addObject:news];
                
                
            }
            //[self.tableView reloadData];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DOWNLOADFINISH" object:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        

    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.allNews.count;
    // NSLog(@"%d",self.allNews.count);
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"news"];
    if (cell==nil) {
        
        cell=[[NewsTableViewCell  alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"news"];
    }
    
    
    
    
    NewsModel *news=self.allNews[indexPath.row];
    //显示的数据
    // ;//dict[@"title"];
    cell.news=news;
    // NSLog(@"%@",((NSDictionary *)arr[indexPath.row])[@"picture"]);
    
    
    
    // Configure the cell...
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel * news=self.allNews[indexPath.row];
    NewscontentViewController *content=[[NewscontentViewController alloc]init];
    content.news=news;
    [self.navigationController pushViewController:content animated:YES];
}
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
